package com.ruoyi.tester.executor.expression;

import com.ruoyi.tester.executor.ExpressionContext;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.stereotype.Component;

/**
 * @author SongJun
 * @description TODO:
 * @date 2021/7/7 17:56
 */
//@Component
//替换为ExpMap
public class ExpJSONObject implements ExpressionAnalysis {
    @Override
    public String getExpressionName() {
        return "JSONObjectValue";
    }

    @Override
    public String getDescription() {
        return "不包含括号和中括号的表达式key, 表示从当前json类型的上下文中获取属性为key的value值;";
    }

    @Override
    public Object analysis(ExpressionContext context, String... param) {
        ExpJSONResult rst = new ExpJSONResult();
        JSONObject node;
        if(context.getContext() instanceof JSONObject){
            node = (JSONObject) context.getContext();
        } else if(context.getContext() instanceof String){
            node = new JSONObject((String)context.getContext());
        } else {
            node = new JSONObject(context.getContext());
        }

        String jsonKey = param[0];
        int questionMark = param[0].indexOf("?");
        if(questionMark > 0) {
            jsonKey = param[0].substring(0, questionMark);
        }

        if(!node.has(jsonKey)){
            if(questionMark > 0){
                rst.value = param[0].substring(questionMark + 1);
                rst.continuous = false;
                return rst;
            } else {
                throw new RuntimeException("解析"+param[1]+"中"+param[0]+"时数据异常");
            }
        }

        if (node.get(jsonKey) instanceof JSONArray) {
            rst.value = node.getJSONArray(jsonKey);
        } else if (node.get(jsonKey) instanceof JSONObject) {
            rst.value = node.getJSONObject(jsonKey);
        } else if (node.get(jsonKey) instanceof String) {
            rst.value = node.getString(jsonKey);
        } else if (node.get(jsonKey) instanceof Long) {
            rst.value = node.getLong(jsonKey);
        } else if (node.get(jsonKey) instanceof Integer) {
            rst.value = node.getInt(jsonKey);
        }
        return rst;
    }

    public static class ExpJSONResult{
        private boolean continuous = true;
        private Object value;

        public boolean isContinuous() {
            return continuous;
        }

        public Object getValue() {
            return value;
        }

        public void setContinuous(boolean continuous) {
            this.continuous = continuous;
        }

        public void setValue(Object value) {
            this.value = value;
        }
    }
}
